//
//  DBHomeController.swift
//  大波微博swift
//
//  Created by 大波 on 16/2/26.
//  Copyright © 2016年 zhaojin. All rights reserved.
//

import UIKit
import SVPullToRefresh

class DBHomeController: DBBaseController {
    
    private let reuseIdentifier = "reuseIdentifier"
    
    var statusesData: [DBStatuses]? {
        
        didSet {
            
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if DBUserAccountViewModel.shareUserAccountViewModel.userAccount == nil {
            
            return
        }
        
        // UI
        setNavigationBar()
        
        perpareTableView()
        
        // 数据
        setRefreshControl()
        
        // 注册通知 监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadLink:", name: DBLoadLinkNotification, object: nil)
    }
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    // MARK: - 数据板块
    
    /// 获取链接通知后触发方法
    @objc private func loadLink(notification: NSNotification) {
        
//        print("notification: \(notification.userInfo)")
        
        // 弹出加载web控制器
        webVC.address = (notification.userInfo?["DBLoadLinkKey"] as? String)
        
        presentViewController(UINavigationController(rootViewController: webVC), animated: true, completion: nil)
    }
    
    private func setRefreshControl() {
        
        // 设置refreshContro
        refreshControl = DBRefreshControl()
        
        refreshControl?.addTarget(self, action: "loadNewStatuses", forControlEvents: UIControlEvents.ValueChanged)
        
        refreshControl?.beginRefreshing()
        
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
        
        // 触发刷新的下拉高度
        refreshControl?.setValue(60, forKey: "_snappingHeight")
    }
    
    
    // 上拉加载更多
    private func pullMoreData() {
        
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            
            self.loadMoreData()
        }
    }
    
    
    @objc private func loadNewStatuses() {
        
        let since_id = statusesData?.first?.id ?? 0
        
        statusesVM.loadStatuses(since_id, max_id: 0) { (statuse, error) -> () in
            
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                
                print("获取statuse出错: \(error)")
                
                return
            }
            
            let count = statuse?.count ?? 0
            
            // 第一次刷新不显示
            if since_id > 0 {
                
                self.showRefreshTipView(count)
            }
            
            // 确保拼接数组强拆有值
            if count == 0 {
                
                return
            }
            
            // 刚开始刷新
            if since_id == 0 {
                
                self.statusesData = statuse
                
                // 第一次下拉加载数据完了后才做上拉加载
                self.pullMoreData()
                
            } else {
                
                //之前有微博数据  拼接数据数组
                self.statusesData = statuse! + self.statusesData!
            }
        }
    }
    
    
    /// 上拉刷新获取之前数据
    private func loadMoreData() {
        
        let max_id = statusesData?.last?.id ?? 0
        
        statusesVM.loadStatuses(0, max_id: max_id) { (statuse, error) -> () in
            
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                
                print("获取statuse出错: \(error)")
                
                return
            }
            
            let count = statuse?.count ?? 0
            
            print("上拉获取数据: \(count)")
            
            if count == 0 {
                
                return
            }
            
            self.statusesData?.removeLast()
            
            self.statusesData = self.statusesData! + statuse!
        }
    }
    
    
    // MARK: - UI板块
    
    // 显示下拉刷新提示框
    private func showRefreshTipView(count: Int) {
        
        tipView.text = count == 0 ? "没有微博更新" : "\(count)条微博更新"
        
        navigationController?.navigationBar.insertSubview(tipView, atIndex: 0)
        
        // 设置动画
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            // 从上往下
            self.tipView.frame.origin.y = 44
            
            }) { (_) -> Void in
                
                // 展示出来后返回上去的动画
                UIView.animateWithDuration(1, animations: { () -> Void in
                    
                    // 从下往上
                    self.tipView.frame.origin.y = -44 - 20
                    
                    }, completion: { (_) -> Void in
                        
                        // 移除
                        self.tipView.removeFromSuperview()
                })
        }
    }
    
    
    private func perpareTableView() {
        
        // 注册cell
        tableView.registerClass(DBStatusesCell.self, forCellReuseIdentifier: reuseIdentifier)
        
        // 预估行高
        tableView.estimatedRowHeight = 260
        
        tableView.rowHeight = UITableViewAutomaticDimension
        
        // 去除分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        tableView.allowsSelection = true
    }
    
    
    private func setNavigationBar() {
        
        setBarButton()
        
        setTitle()
    }
    
    
    private func setBarButton() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
    }
    
    
    private func setTitle() {
        
        let titleButton = DBTitleView(title: "我是标题")
        
        titleButton.addTarget(self, action: "titleButtonDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = titleButton
    }
    
    
    // 标题按钮触发方法
    @objc private func titleButtonDidClick(button: DBTitleView) {
        
        button.selected = !button.selected
        
        // 标题按钮动画
        UIView.animateWithDuration(0.4) { () -> Void in
            
            button.selected ? (button.imageView?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI) - 0.01)) : (button.imageView?.transform = CGAffineTransformIdentity)
        }
        
        // 标题按钮为选中状态弹出popover
        if button.selected {
            
            let sb = UIStoryboard(name: "DBPopover", bundle: nil)
            
            let popoverVC = sb.instantiateInitialViewController()
            
            popoverVC?.modalPresentationStyle = UIModalPresentationStyle.Popover
            
            popoverVC?.popoverPresentationController?.delegate = self
            
            popoverVC?.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up
            
            popoverVC?.popoverPresentationController?.sourceView = navigationItem.titleView
            
            popoverVC?.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
            
            popoverVC?.preferredContentSize = CGSizeMake(200, 5 * 44)
            
            presentViewController(popoverVC!, animated: true, completion: nil)
        }
    }
    
    
    // MARK: - 懒加载
    
    private lazy var statusesVM: DBStatusesViewModel = DBStatusesViewModel()
    
    private lazy var tipView: UILabel = {
    
        let label = UILabel(textColor: UIColor.blueColor(), font: 14)
        
        label.frame = CGRect(origin: CGPoint(x: 0, y: -44 - 20), size: CGSize(width: UIScreen.width, height: 44))
        
        label.backgroundColor = UIColor.orangeColor()
        
        label.textAlignment = NSTextAlignment.Center
        
        return label
    }()
    
    private lazy var webVC: DBHomeWebController = DBHomeWebController()
}




// MARK: - UIPopoverPresentationControllerDelegate

extension DBHomeController: UIPopoverPresentationControllerDelegate {
    
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        
        return UIModalPresentationStyle.None
    }
    
    func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
        
        let btn = navigationItem.titleView as! DBTitleView
        
        titleButtonDidClick(btn)
    }
}



// MARK: - Table view data source

extension DBHomeController {
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusesData?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! DBStatusesCell
        
        cell.statuse = self.statusesData?[indexPath.row]
        
        return cell
    }
    
    // 是否需要高亮
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
    
//        override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//            // 取消选中 但是仍会有高亮出现
//            tableView.deselectRowAtIndexPath(indexPath, animated: false)
//        }
}










